package com.example.su_shi_tan_core

import android.content.Context
import android.util.Log
import androidx.work.Worker
import androidx.work.WorkerParameters
import com.alibaba.fastjson.JSON
import com.example.library_common.utils.normalShortToast
import com.example.su_shi_tan_bas_lib.global.AppGlobals
import com.example.su_shi_tan_bas_lib.networking.RestClient
import com.example.su_shi_tan_bas_lib.utils.even.MessageWrap
import com.example.su_shi_tan_bas_lib.utils.even.TO_REFRESH_USER_INFO
import com.example.su_shi_tan_core.constant.LOG_IN_AGAIN
import com.example.su_shi_tan_core.constant.LOG_IN_AGAIN_1
import com.example.su_shi_tan_core.db.LogInTokenManager
import com.example.su_shi_tan_core.db.UserInfoBeanHolder
import org.greenrobot.eventbus.EventBus

class UserInfoDataWorker(context: Context, param: WorkerParameters) : Worker(context, param) {
    override fun doWork(): Result {

        if (!LogInTokenManager.tokenManager.haveSignedIn()) return Result.success()

        RestClient.builder()
            .url(R.string.queryUserByUid)
            .success {
//                Log.d("onSupportVisible", "queryUserByUid: $it")
//                val parse = JSON.parseObject(it)
//                val userInfoStr = parse["userInfo"]
//                val userInfoNew = JSON.parseObject(userInfoStr.toString(), UserInfo::class.java)
//                userInfoWrapper?.userInfo = userInfoNew
//                userInfoNew.UserInfoTemple= JSON.toJSONString(userInfoStr)
//                userInfoManager.saveUserInfoWrapper(userInfoWrapper)
                UserInfoBeanHolder.onSave(it)
                EventBus.getDefault().post(MessageWrap.getInstance(TO_REFRESH_USER_INFO))

            }.failure {
                normalShortToast(AppGlobals.getApplication(), R.string.user_info_failed)
                EventBus.getDefault().post(MessageWrap.getInstance(TO_REFRESH_USER_INFO))

            }.error { code, msg ->
                if (code == LOG_IN_AGAIN || code == LOG_IN_AGAIN_1) {
                    signOut()
                }
                normalShortToast(AppGlobals.getApplication(), msg)

                EventBus.getDefault().post(MessageWrap.getInstance(TO_REFRESH_USER_INFO))
            }
            .build()
            .get()

        return Result.success()
    }
}